<!--
 * @Author: DT1604\ZPL zhoupeili@dpc.com.cn
 * @Date: 2022-09-19 13:43:36
 * @LastEditors: DT1604\ZPL zhoupeili@dpc.com.cn
 * @LastEditTime: 2022-09-20 13:42:10
 * @FilePath: \eoms-ui\src\views\facturer\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="app-container">
    <el-form class="searchForm" :inline="true" size="mini" ref="searchForm" :model="searchForm" label-width="60px">
      <!-- //平台用户展示 -->
      <el-form-item label="厂商" v-if="platformType == 'P'">
        <el-select v-model="searchForm.organId" placeholder="请选择厂商" clearable>
          <el-option v-for="item in factuerOption" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="运营商">
        <el-input v-model="searchForm.name" clearable placeholder="请输入运营商名称" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="doSearch">搜索</el-button>
        <el-button type="default" size="mini" icon="el-icon-refresh" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="searchs-content" v-permission="['equip:operator:insert']">
      <el-button type="primary" size="mini" plain icon="el-icon-plus" @click="addDialog">新增</el-button>
    </div>
    <Table :tableHeader="tableHeader" :tableData="tableData" :tableLoading="listLoading">
      <template slot="action" slot-scope="scope">
        <el-button type="primary" size="mini" @click="addDialog(scope.row)"
          v-permission="['equip:operator:update']">编辑</el-button>
        <el-button type="danger" size="mini" @click="deleteRow(scope.row)"
          v-permission="['equip:operator:delete']">删除</el-button>
      </template>
    </Table>
    <pagination v-if="total>0" :total="total" :page.sync="searchForm.pageNum" :limit.sync="searchForm.pageSize"
      @pagination="fetchData" />

    <!-- 弹框 -->
    <Dialog :visible="visible" width="30%" :title="dialogTitle" :loading="dialogBtnLoading" @confirmDialog="confirmDialog"
      @cancelDialog="cancelDialog">
      <el-alert class="tips" title="备注：请厂商管理员添加运营商分公司或者子公司时，除非非常明确不会引起歧义，须采用运营商分公司、子公司正式名称，避免搜索产生多重结果，不要只写省市地名。"
        type="error" :closable="false">
      </el-alert>
      <el-form ref="dialogForm" :model="dialogForm" label-width="100px" :rules="dialogRules" size="small">
        <el-form-item label="厂商" prop="organizationId">
          <el-select :disabled="dialogForm.id ? true : false" v-model="dialogForm.organizationId" clearable placeholder="请选择厂商">
            <el-option v-for="item in factuerOption" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="运营商名称" prop="name">
          <el-input v-model="dialogForm.name" clearable placeholder="请输入运营商名称" />
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import { factuerManage, operator } from "@/api/factuer";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import Table from "@/components/Table";
import Dialog from "@/components/Dialog";
import moment from "moment";

import { handleConfirm } from "@/utils/messageBox";
import { removeNullUndefined } from "@/utils/index.js";

export default {
  components: { Pagination, Table, Dialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      listLoading: true,
      total: 0,
      searchForm: {
        pageNum: 1,
        pageSize: 15,
        name: "",
        organId: "",
      },

      tableHeader: [
        {
          type: "index",
          label: "序号",
          width: "60",
          fixed: true,
        },
        {
          label: "运营商名称",
          prop: "name",
        },
        {
          label: "操作人",
          prop: "updateBy",
        },

        {
          label: "更新时间",
          prop: "updateTime",
          formatter: (item) => {
            return item.updateTime
              ? moment(item.updateTime).format("YYYY-MM-DD HH:mm:ss")
              : "";
          },
        },
        { slot: "action", label: "操作", width: "180" },
      ],
      tableData: [],
      visible: false, //弹框标识
      dialogForm: {
        name: "",
        organizationId: "",
      },
      dialogRules: {
        name: [
          { required: true, message: "请输入运营商名称", trigger: "blur" },
        ],
        organizationId: [
          { required: true, message: "请选择厂商", trigger: "change" },
        ],
      },
      dialogTitle: "",
      dialogBtnLoading: false,
      factuerOption: [],
      platformType: this.$store.state.user.platformType,
      organizationId: this.$store.state.user.organizationId,
    };
  },
  created() {
    if (this.platformType != "P") {
      //非平台用户
      this.searchForm.organId = this.organizationId;
    } else {
      this.getFactuerList();
    }
    this.fetchData();
  },
  methods: {
    fetchData(val) {
      this.searchForm.pageNum = val ? val.page : this.searchForm.pageNum;
      this.listLoading = true;
      this.tableData = [];
      this.total = 0;
      operator("/list", "get", {
        ...removeNullUndefined(this.searchForm),
      })
        .then((res) => {
          this.tableData = res.data;
          this.total = +res.total;

          this.searchForm.pageNum = +res.pageNum;
        })
        .finally(() => {
          this.listLoading = false;
        });
    },
    async getFactuerList() {
      let datas = await factuerManage("/all", "post");
      this.factuerOption = datas.data;
    },
    // 弹框取消
    cancelDialog() {
      this.visible = false;
      this.resetDialogForm("dialogForm");
      this.dialogForm= {
        name: "",
        organizationId: "",
      };
    },
    // 弹框确认
    confirmDialog() {
      this.submitDialogForm("dialogForm");
    },
    // 新增
    addDialog(row) {
      this.visible = true;
      this.dialogForm = {
        name: "",
        organizationId: "",
      };
      if (this.factuerOption.length == 0) {
        this.getFactuerList();
      }
      if (row.id) {
        this.dialogTitle = "编辑";
        this.dialogForm = { ...row };
      } else {
        this.dialogTitle = "新增";
      }
    },
    submitDialogForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let msg = this.dialogForm.id ? "编辑" : "新增";
          handleConfirm(`确定要${msg}运营商信息吗？`, "warning", "提示")
            .then((res) => {
              this.doAdd();
            })
            .catch((err) => {
              // do something cancel
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    doAdd() {
      this.dialogBtnLoading = true;
      let { id, name } = this.dialogForm;

      let url = this.dialogForm.id ? `/rename/${id}` : "/insert";
      // let method = this.dialogForm.id ? "get" : "post";
      let param = this.dialogForm.id ? { name } : this.dialogForm;
      operator(url, "post", param)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.visible = false;
            this.fetchData();
          }
        })
        .finally(() => {
          this.dialogBtnLoading = false;
        });
    },
    resetDialogForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 删除
    deleteRow(row) {
      //确认弹窗
      handleConfirm("删除后不可恢复，确定执行此操作吗？", "warning", "提示")
        .then((res) => {
          this.doDelete(row);
        })
        .catch((err) => {
          // do something cancel
        });
    },
    doDelete(row) {
      operator(`/delete/${row.id}`, "post").then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.visible = false;
          this.fetchData();
        }
      });
    },
    resetSearch() {
      this.searchForm = {
        pageNum: this.searchForm.pageNum,
        pageSize: this.searchForm.pageSize,
        name: "",
        organId: this.platformType != "P" ? this.organizationId : "",
      };
    },
    doSearch() {
      this.searchForm.pageNum = 1;
      this.fetchData();
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.searchForm {
    .el-form-item {
        margin-bottom: 8px;
    }
}
.tips {
  margin-bottom: 15px;
}
::v-deep .el-input.is-disabled .el-input__inner {
  color: #000000;
}
</style>